package com.ajie.utils;


import com.ajie.vo.MailVo;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.util.Arrays;

/**
 * 发送邮件的工具类
 */
@Slf4j
@Component
public class MailUtils {

    @Autowired
    private JavaMailSender mailSender;
    
    @Value("${spring.mail.username}")
    private String from;
    
    public String  sendMail(MailVo mailVo){
        log.info("该文件名是：MailUtils,该方法是：sendMail");
        try {
            if (mailVo.isHtml()){
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
                messageHelper.setFrom(from);
                messageHelper.setTo(mailVo.getReceivers());
                messageHelper.setSubject(mailVo.getSubject());
                messageHelper.setText(mailVo.getContent(),true);
                mailSender.send(mimeMessage);
                log.info("HTML邮件发送成功！收件人---{}---", Arrays.asList(mailVo.getReceivers()));
            }else {
                //创建邮件对象
                SimpleMailMessage mailMessage = new SimpleMailMessage();
                //发件人
                mailMessage.setFrom(from);
                //收件人
                mailMessage.setTo(mailVo.getReceivers());
                //邮件主题
                mailMessage.setSubject(mailVo.getSubject());
                //邮件内容
                mailMessage.setText(mailVo.getContent());
                mailSender.send(mailMessage);
                log.info("普通邮件发送成功！！收件人---{}---", Arrays.asList(mailVo.getReceivers()));
            }
            return "邮件发送成功";
        }catch (Exception e){
            log.error("邮件发送失败-->{}",e.getMessage());
            return "邮件发送失败";
        }
        
    }


}
